import LayerGroup from "ol/layer/Group";
import TileLayer from "ol/layer/Tile";
import { XYZ } from "ol/source";

import { get as getProjection } from "ol/proj";
import { getTopLeft, getWidth } from "ol/extent";
import WMTSTileGrid from "ol/tilegrid/WMTS";


export default class Tianditu {
    #baseUrl = "http://t{0-7}.tianditu.gov.cn/";
    #tk = '5309fa70248bb4442cb5cc0344e25743';
    #sourceGroupType = {
        vec: ['vec', 'cva'],
        img: ['img', 'cia'],
    }
    // 瓦片图层组
    createTileLayerGroup(type, visible) {
        const layers = this.#sourceGroupType[type].map((st) => {
            return this.createTileLayer(st)
        })

        return new LayerGroup({
            layers,
            visible,
            properties: {
                name: type
            }
        })
    }
    // 瓦片图层
    createTileLayer(type) {
        return new TileLayer({
            source: this.createXYZSource(type)
        })
    }
    // 瓦片地图资源
    createXYZSource(type) {
        return new XYZ({
            url: this.#baseUrl +
                type +
                "_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=" +
                type +
                "&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=" +
                this.#tk,
            tileGrid: createTileGrid(getProjection("EPSG:3857")),
        })
    }
}
// 创建瓦片网格模式，天地图只支持到18级，不扩展18级之后会出现空白
function createTileGrid(projection) {
    const projExtent = projection.getExtent();
    const origin = getTopLeft(projExtent);
    const width = getWidth(projExtent);
    const resolutions = new Array(18);
    const matrixIds = new Array(18);
    for (let z = 0; z < 18; ++z) {
      resolutions[z] = width / (256 * Math.pow(2, z));
      matrixIds[z] = z;
    }
    return new WMTSTileGrid({
      origin,
      resolutions,
      matrixIds,
    });
}